package com.yinhai.message.search.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.yinhai.core.common.api.base.IPage;
import com.yinhai.message.api.util.MessageType;
import com.yinhai.message.implement.dwr.util.RedisTool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yinhai.core.app.ta3.web.controller.BaseController;
import com.yinhai.message.core.po.MessageFilePo;
import com.yinhai.message.search.bpo.IMessageSearchBpo;
import com.yinhai.message.search.vo.MessageInfoVo;

/**
 * 
 * @author yanglq
 * 2017.6.20
 */
@RequestMapping("messageHttp")
@Controller
public class MessageSearchController extends BaseController{
	
	@Resource
	private IMessageSearchBpo messageSearchBpo;
	
	@RequestMapping("messageSearchController!queryMessage.do")
	@ResponseBody
	public Object queryMessage(@RequestParam(name = "searchParameter", required = true) String searchParameter,
							   HttpServletResponse response){

		response.setHeader("Access-Control-Allow-Origin", "*");
		if(searchParameter.length()==0){
			return null;
		}
		Map<String,Object> parameter = com.alibaba.fastjson.JSON.parseObject(searchParameter, Map.class);
		if (!(parameter.containsKey("userid") && parameter.containsKey("systemid"))) {
			return null;
		}
		List<MessageInfoVo> listVo;
		if(parameter.containsKey("beginDate") && parameter.containsKey("endDate")){
			listVo = messageSearchBpo.queryMessage(parameter);
		}else{
			String messageType = MessageType.DWR;
			if(parameter.containsKey("messageType")){
				messageType = (String)parameter.get("messageType");
			}
			listVo = messageSearchBpo.getMessage((String)parameter.get("systemid"),(String)parameter.get("userid"),null,200,messageType);
		}
//		List<MessageInfoVo> listVo = messageSearchBpo.queryMessage(parameter);
		return handleData(listVo);
	}

	@RequestMapping("messageSearchController!pollQueryMessage.do")
	@ResponseBody
	public Object pollQueryMessage(@RequestParam(name = "searchParameter", required = true) String searchParameter,
								   HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		if(searchParameter.length()==0){
			return null;
		}
		Map<String,Object> parameter = com.alibaba.fastjson.JSON.parseObject(searchParameter, Map.class);
		if (!(parameter.containsKey("userid") && parameter.containsKey("systemid"))) {
			return null;
		}
		List<MessageInfoVo> listVo;
		if(parameter.containsKey("beginDate") && parameter.containsKey("endDate")){
			listVo = messageSearchBpo.queryMessage(parameter);
		}else{
			String messageType = MessageType.DWR;
			if(parameter.containsKey("messageType")){
				messageType = (String)parameter.get("messageType");
			}
			listVo = messageSearchBpo.getPollMessage((String)parameter.get("systemid"),(String)parameter.get("userid"),null,200,messageType);
		}
//		List<MessageInfoVo> listVo = messageSearchBpo.queryMessage(parameter);
		return handleData(listVo);
	}

	@RequestMapping("messageSearchController!queryAppMessage.do")
	@ResponseBody
	public Object queryAppMessage(@RequestParam(name = "searchParameter", required = true) String searchParameter){
		if(searchParameter.length()==0){
			return null;
		}
		Map<String,Object> parameter = com.alibaba.fastjson.JSON.parseObject(searchParameter, Map.class);
		if (!(parameter.containsKey("aac001")
				&& parameter.containsKey("beginDate") 
				&& parameter.containsKey("endDate"))) {
			return null;
		}
		List<MessageInfoVo> listVo = messageSearchBpo.queryAppMessage(parameter);
		List<Map<String,String>> listMap = new ArrayList<>();
    	for(MessageInfoVo vo :listVo){
    		Map<String,String> msg = new HashMap<>();
			msg.put("mgid", String.valueOf(vo.getMgid_app()));
			msg.put("title", vo.getTitle());
			msg.put("content", vo.getContent());
			msg.put("mgdateShow", vo.getMgdateShow());
			listMap.add(msg);
    	}
		return listMap;
	}

	@RequestMapping("messageSearchController!readMessage.do")
	@ResponseBody
	public Object readMessage(@RequestParam(name = "mgid", required = true) String mgid,
							  @RequestParam(name = "systemid", required = true) String systemid,
							  @RequestParam(name = "userid", required = true) String userid,
							  @RequestParam(name = "messageType") String messageType,
							   HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		if(messageType==null) messageType=MessageType.DWR;
		messageSearchBpo.setMessageRead(mgid, systemid, userid,messageType);
		return "success";
	}

	@RequestMapping("messageSearchController!userOnline.do")
	@ResponseBody
	public Object userOnline(@RequestParam(name = "systemid", required = true) String systemid,
							 @RequestParam(name = "userid", required = true) String userid,
							 @RequestParam(name = "online", required = true) String online,
									HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			RedisTool.getInstance().userOnLine(systemid,userid,online);
		}catch (Exception e){
			return "redis异常，联系管理员"+e.getMessage();
		}
		return "success";
	}
	@RequestMapping("messageSearchController!getMessageByCache.do")
	@ResponseBody
	public Object getMessageByCache(@RequestParam(name = "systemid", required = true) String systemid,
									@RequestParam(name = "userid", required = true) String userid,
							  HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin", "*");
		Map<String,String> msgMap = null;
		try {
			msgMap = RedisTool.getInstance().getMessage(systemid,userid);
		}catch (Exception e){
			return "redis异常，联系管理员"+e.getMessage();
		}
		List<Map<String,String>> listMap = new ArrayList<>();
		if(msgMap!=null){
			for (Map.Entry<String,String> entry : msgMap.entrySet()) {
				Map<String, String> msg = com.alibaba.fastjson.JSON.parseObject(entry.getValue(),Map.class);
				listMap.add(msg);
			}
		}
		return listMap;
	}

	@RequestMapping("messageSearchController!queryMessageForPage.do")
	@ResponseBody
	public Object queryMessageForPage(@RequestParam(name = "searchParameter", required = true) String searchParameter,
									  HttpServletResponse response) throws Exception{
		response.setHeader("Access-Control-Allow-Origin", "*");
		if(searchParameter.length()==0){
			return null;
		}
		Map<String,Object> parameter = com.alibaba.fastjson.JSON.parseObject(searchParameter, Map.class);
		if (!(parameter.containsKey("userid") && parameter.containsKey("systemid"))) {
			return null;
		}
		String messageType = MessageType.DWR;
		if(parameter.containsKey("messageType")){
			messageType = (String)parameter.get("messageType");
		}
		//查询分页
		IPage<MessageInfoVo> page = messageSearchBpo.queryMessageForPage((String)parameter.get("systemid"),(String)parameter.get("userid"),messageType,(int)parameter.get("page"),(int)parameter.get("limit"));
		List<Map<String,String>> listMap = new ArrayList<>();
		List<Map<String,String>> readMap;
		List<Map<String,String>> unReadMap;
		List<MessageInfoVo> readList = new ArrayList<>();
		List<MessageInfoVo> unReadList = new ArrayList<>();
		//组装数据  按照已读未读分开  使未读在前
		for(MessageInfoVo vo :page.getList()){
			if("1".equals(vo.getRead())){
				readList.add(vo);
			}else{
				unReadList.add(vo);
			}
		}
		readMap = handleData(readList);
		unReadMap = handleData(unReadList);
		listMap.addAll(unReadMap);
		listMap.addAll(readMap);
		//返回分页对象
		Map<String,Object> resultMap  =new HashMap<>();
		resultMap.put("total",page.getTotal());
		resultMap.put("list",listMap);
		return resultMap;
	}

	private List<Map<String,String>> handleData(List<MessageInfoVo> listVo){
		List<Map<String,String>> listMap = new ArrayList<>();
		for(MessageInfoVo vo :listVo){
			StringBuilder fileStr = new StringBuilder("附件：<br>");
			if("file".equals(vo.getSelfType())){
				List<MessageFilePo> listFilePo = messageSearchBpo.getMessageFile(vo.getMgid());
				for(MessageFilePo filePo:listFilePo){
					fileStr.append(filePo.getFilename())
							.append(":<a id='")
							.append(filePo.getId())
							.append("' href='javascript:mgAtmDownload(")
							.append(filePo.getId())
							.append(")' style='color: #1A5E9E;cursor: pointer'>下载</a>")
							.append("<br>");
				}
			}
			Map<String,String> msg = new HashMap<>();
			msg.put("mgid", vo.getMgid());
			msg.put("title", vo.getTitle());
			msg.put("content", vo.getContent());
			msg.put("attachment", fileStr.toString());
			msg.put("mgdateShow", vo.getMgdateShow());
			msg.put("suserid", vo.getSuserid());
			msg.put("sname", vo.getSname());
			msg.put("read", vo.getRead());
			msg.put("selfType", vo.getSelfType());
			msg.put("otherData1", vo.getOtherData1());
			msg.put("otherData2", vo.getOtherData2());
			msg.put("otherData3", vo.getOtherData3());
			listMap.add(msg);
		}
		return listMap;
	}
}
